//初始化
$(function(){	
	//form关闭按钮
	$('.b-btn-cancel').click(function() {
		utils.closeLayer();
	});
	function initSelect() {
		if($.fn.select2 != null) {
			$(".simpleSelect").select2({width:'100%',minimumResultsForSearch:-1}); //没有查询栏
			$(".querySelect").select2({width:'100%'}); //有查询栏	
		}
	}
	function initBootstrptable() {
		if($.fn.bootstrapTable != null) {			
			//bootrap table 初始配置
			$.fn.bootstrapTable.defaults.queryParams = function(params) {
				return tbutils.defineParams(params);
			};
			$.fn.bootstrapTable.defaults.queryParamsType = '';
			$.fn.bootstrapTable.defaults.undefinedText = '';
			$.fn.bootstrapTable.defaults.sidePagination = 'server';
			$.fn.bootstrapTable.defaults.dataType = 'json';
			$.fn.bootstrapTable.defaults.striped = true;
			$.fn.bootstrapTable.defaults.pagination = true; //是否分页
			$.fn.bootstrapTable.defaults.showColumns = true; //是否显示所有的列
			$.fn.bootstrapTable.defaults.showRefresh = true; //是否显示刷新按钮
			$.fn.bootstrapTable.defaults.clickToSelect = true;
		}
	}
	initSelect();
	initBootstrptable();
});

//表格处理
var tbutils = {
	defineParams: function(params){
		return {
			page: params.pageNumber,
			limit: params.pageSize,
			sortOrder: params.sortOrder,
			v: new Date().getTime()
		}
	},	
	__getSelects: function($table) {
		var datas = $table.bootstrapTable('getSelections');
		return datas;
	},
	getMulSelect: function($table) {
		var datas = this.__getSelects($table);
		if(datas.length <= 0) {
			layer.alert('请选择操作的记录');
			return null;
		}
		return datas;
	},
	getOneSelect: function($table) {
		var datas = this.__getSelects($table);
		if(datas.length != 1) {
			layer.alert('请选择一行记录操作');
			return null;
		}else {
			return datas[0];
		}
	},
	extParams: function(params, myParams) {
		var tm = this.defineParams(params);
		var query = $.extend( true, tm, myParams);
        return query;
	}
}

//业务结合的代码
var bizutils = {
	menuTree: function() {
		
	}	
}

//工具类
var utils = {
	getLayerWin: function(layero) {
		return $(layero).find('iframe')[0].contentWindow;
	},
	//获取layer的中的jquery	
	getLayerJq: function(layero) {
		return this.getLayerWin(layero).$;
	},
	isFrame: function () { //判断frame
		if(self != top) {
			return true;
		}else {
			return false;
		}
	},
	tipMsg: function(msg, url) { //显示信息
		if (this.isFrame()) {
			//在iframe中
			parent.layer.alert(msg,{closeBtn: 0},function(index){
				if(url != null) {
					
				}
				parent.layer.close(index);
			});
		}else {
			layer.alert(msg,{closeBtn: 0},function(index){
				if(url != null) {
				}
				layer.close(index);
			});
		}
	},
	globalStatus: function (xhr,status) {
		switch (xhr.status) {
		case 400:
			tipMsg('请求参数不合法',null);
			break;
		case 401:
			tipMsg('登录已经超时，请重新登录','loginControl/login');
			break;
		case 404:
			tipMsg('请求路径出现错误',null);
			break;
		case 405:
			tipMsg('不支持该方式访问',null);
			break;
		case 403:
			tipMsg('无权限执行此操作',null);
			break;
		case 500:
			tipMsg('服务器出现错误，请联系管理员',null);
			break;			
		}
	},
	plyopen: function(args) {
		 if(args.area == null) {
	            args.area = ['600px', '550px']
	        }
	        parent.layer.open({
	            type: 2,
	            title:args.title,
	            area: args.area,
	            fixed: false, //不固定
	            maxmin: true,
	            content: [args.content],
	            end: args.end,
	            btn: args.btn,
	            yes: args.yes
	        });
	},
	 //用于保存弹窗
	lyopen: function(args) {
        if(args.area == null) {
            args.area = ['600px', '550px']
        }
        layer.open({
            type: 2,
            title:args.title,
            area: args.area,
            fixed: false, //不固定
            maxmin: true,
            content: [args.content],
            end: args.end,
            btn: args.btn,
            yes: args.yes
        });
	},
	closeLayer: function() {
		var index = parent.layer.getFrameIndex(window.name);
		parent.layer.close(index);
	},
	confirm: function(msg, fun) {
		layer.confirm(msg, {icon: 3}, function(index){
			fun();
			layer.close(index);
		});
	},
	alert: function(msg, fun) {
		layer.alert(msg, {closeBtn:0}, function(index) {
			if(fun != null) {
				fun();
			}
			layer.close(index);
		});
	},
	palert: function(msg,fun) { //父级弹框
		parent.layer.alert(msg,{closeBtn:0},function(index) {
			if(fun != null) {
				fun();
			}
			parent.layer.close(index);
		});
	}
}

//jquery扩展
$.fn.extend({
	//表单序列化成json
	serializeJson: function() {
		var serializeObj = {};
		var array = this.serializeArray();
		var str = this.serialize();
		$(array).each(
				function() {
					if (serializeObj[this.name]) {
						if ($.isArray(serializeObj[this.name])) {
							serializeObj[this.name].push(this.value);
						} else {
							serializeObj[this.name] = [
									serializeObj[this.name], this.value ];
						}
					} else {
						serializeObj[this.name] = this.value;
					}
				});
		return serializeObj;
	}
});

$.extend({
	loadReq: function(args) {
		var loadIndex = layer.load(1);
		if(args.contentType == null) {
			args.contentType = 'application/x-www-form-urlencoded';
		}
		$.ajax({
			type:args.type,
			url:args.url,
			data:args.data,
			success:args.success,
			contentType: args.contentType,
			complete:function(xhr,status) {
				layer.close(loadIndex);
				//globalStatus(xhr,status);
			},
			error:function(xhr,status) {
				layer.close(loadIndex);
				//globalStatus(xhr,status);
			}
		});
	}
});

//jquery validator 校验扩展
if($.validator != null) {
	//正则校验
	$.validator.addMethod('pattern', function(value, element, param) {
		return this.optional(element) || param.test(value);
	}, '格式不匹配');
}


function valid(){
	//验证手机号码
	this.mobile=function(value){
		//num=num.replace(/\(|\)|\s+|-/g,'');
		return /^1[3|4|5|7|8]\d{9}$/i.test(value);
	};
	//验证字符是否超长
	this.isOverLength=function(value,max_length){
		return value.length>max_length?true:false;
	};
	//验证日期格式
	this.date=function(value){
		return /^[1-9]{1}\d{3}[-|\/|\.]\d{1,2}[-|\/|\.]\d{1,2}(\s+\d{1,2}:\d{1,2}(:\d{1,2})?)?$/.test(value);
	};
	//是否为空
	this.isEmpty=function(value){
		if(value != null && value != undefined) {
			return !/\S/.test(value);
		}else {
			return true;
		}
	};
	//验证邮箱格式
	this.email=function(value){
		return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value);
	};
	//验证金额格式
	this.price=function(value){
		return this.isEmpty(value)?false:/^[+-]?([1-9]{1}\d{0,2}(,\d{3})*(\.\d{0,2})?|[1-9]{1}\d*(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2})?)$/.test(value);
	};
	//是否为数字
	this.isNum=function(value){
		return this.isEmpty(value)?false:/^[+-]?([1-9]{1}\d{0,2}(,\d{3})*(\.\d*)?|[1-9]{1}\d*(\.\d*)?|0(\.\d*)?|(\.\d+)?)$/.test(value);
	};
	//是否正整数
	this.isPInt=function(value){
		return /^\d+$/.test(value);
	};
	//是否整数
	this.isInt=function(){
		return this.isEmpty(value)?false:/^-?\d+$/.test(value);
	};
	//日期比较
	this.isDateBeginEnd=function(begin,end){
		if(!this.date(begin)||!this.date(end))
			return false;
		begin=new Date(begin.replace(/-|\./g,'/')).getTime();
		end=new Date(end.replace(/-|\./g,'/')).getTime();
		return begin>end?false:true;
	};
	//验证身份证号码格式
	this.idCard=function(value){
		return /^[1-9]{1}[0-9]{14}$|^[1-9]{1}\d{16}[\dxX\*]$/.test(value);
	};
}
var validation=new valid();
//bootstrap jquery validator 扩展
;!function(a){var b=0,c=0;a.extend(!0,a.validator,{prototype:{defaultShowErrors:function(){var d=this,e=a.fn.tooltip.Constructor.VERSION;e&&(e=e.split("."),b=parseInt(e[0]),c=parseInt(e[1])),a.each(this.errorList,function(e,f){if(3===b&&c>=3){var g=a(f.element);void 0!==g.data("bs.tooltip")?g.data("bs.tooltip").options.title=f.message:g.tooltip(d.applyTooltipOptions(f.element,f.message)),a(f.element).removeClass(d.settings.validClass).addClass(d.settings.errorClass).tooltip("show")}else a(f.element).removeClass(d.settings.validClass).addClass(d.settings.errorClass).tooltip(4===b?"dispose":"destroy").tooltip(d.applyTooltipOptions(f.element,f.message)).tooltip("show");d.settings.highlight&&d.settings.highlight.call(d,f.element,d.settings.errorClass,d.settings.validClass)}),a.each(d.validElements(),function(c,e){a(e).removeClass(d.settings.errorClass).addClass(d.settings.validClass).tooltip(4===b?"dispose":"destroy"),d.settings.unhighlight&&d.settings.unhighlight.call(d,e,d.settings.errorClass,d.settings.validClass)})},applyTooltipOptions:function(c,d){var e;e=4===b?a.fn.tooltip.Constructor.Default:3===b?a.fn.tooltip.Constructor.DEFAULTS:a.fn.tooltip.defaults;var f={animation:a(c).data("animation")||e.animation,html:a(c).data("html")||e.html,placement:a(c).data("placement")||e.placement,selector:a(c).data("selector")||e.selector,title:a(c).attr("title")||d,trigger:a.trim("manual "+(a(c).data("trigger")||"")),delay:a(c).data("delay")||e.delay,container:a(c).data("container")||e.container};return this.settings.tooltip_options&&this.settings.tooltip_options[c.name]&&a.extend(f,this.settings.tooltip_options[c.name]),this.settings.tooltip_options&&this.settings.tooltip_options._all_&&a.extend(f,this.settings.tooltip_options._all_),f}}})}(jQuery);
